import { EyeOutlined, DeleteOutlined } from '@ant-design/icons'
import { truthy } from '@gnlab/utils'
import { Spin, message, Table, Popconfirm } from 'antd'
import { Modal, Empty } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import services from '@/services'
import { chatFlowBoundStatusTexts } from '@/services/features/chat-flows'
import type { ChatFlow, ChatFlowContact } from '@/services/features/chat-flows'
import ApplyRecords from './ApplyRecords'
import './Detail.module.less'

export default function Detail(props: { showing: ChatFlow | null; onClose: () => void }) {
  const { showing, onClose } = props

  return <Modal
    open={!!showing}
    onCancel={onClose}
    title={`${showing?.name ?? ''} - 执行详情`}
    width="800px"
    footer={null}
  >
    {showing ? <Content flow={showing} /> : null}
  </Modal>
}

function Content(props: { flow: ChatFlow }) {
  const { flow } = props

  const [contacts, setContacts] = useState<ChatFlowContact[] | null>(null)

  const load = useCallback(async () => {
    const res = await services.features.chatFlows.getContactsOfFlow(flow.id)
    if (res.success) setContacts(res.data)
    else void message.error(`执行详情加载失败：${res.error}`)
  }, [flow])
  useEffect(() => void load(), [load])

  const unbind = useCallback(
    async (contact: ChatFlowContact) => {
      const res = await services.features.chatFlows.unbind(contact.contactId)
      if (!res.success) void message.error(`删除失败：${res.error}`)
      void load()
    },
    [load],
  )

  const [showingRecords, setShowingRecords] = useState<ChatFlowContact | null>(null)

  // ===========================================================

  const renderContact = useCallback(
    (contact: ChatFlowContact) => {
      const contactName = flow.forGroup
        ? services.groups.list.value.get(contact.contactId)?.name ?? ''
        : contact.name
      return <div>
        <img src={contact.avatar || defaultAvatar} />
        <div styleName="info">
          <div styleName="name">{contactName}</div>
          <div styleName="user-id">ID: {contact.userId}</div>
        </div>
      </div>
    },
    [flow],
  )

  const renderQywx = useCallback((contact: ChatFlowContact) => {
    return <>
      {contact.ownerNickname
        ? `${contact.ownerNickname}（${contact.ownerUsername}）`
        : contact.ownerUsername}
    </>
  }, [])

  const renderStatus = useCallback((contact: ChatFlowContact) => {
    return chatFlowBoundStatusTexts[contact.status]
  }, [])

  const renderActions = useCallback(
    (contact: ChatFlowContact) => {
      return <>
        <EyeOutlined styleName="show-records" onClick={() => setShowingRecords(contact)} />

        <Popconfirm
          title="删除后，此工作流尚未执行的工作项目将不会被执行。确认删除？"
          onConfirm={() => void unbind(contact)}
        >
          <DeleteOutlined styleName="remove" />
        </Popconfirm>
      </>
    },
    [unbind],
  )

  const loading = <div styleName="loading">
    <Spin tip="加载中..." size="large" />
  </div>

  const empty = <div styleName="empty">
    <Empty description="没有联系人应用此工作流" />
  </div>

  return <div>
    {!contacts ? loading : null}
    {contacts && !contacts.length ? empty : null}
    {truthy(contacts?.length) ? (
      <Table<ChatFlowContact>
        rowKey="contactId"
        dataSource={contacts!}
        scroll={{ y: 500 }}
        pagination={false}
      >
        <Table.Column<ChatFlow>
          title="客户"
          key="contact"
          render={renderContact}
          styleName="contact"
        />
        <Table.Column<ChatFlow>
          title="归属企业微信"
          key="qywx"
          render={renderQywx}
          styleName="qywx"
          width="180px"
        />
        <Table.Column<ChatFlow> title="状态" key="status" render={renderStatus} width="120px" />
        <Table.Column<ChatFlow>
          title="操作"
          key="actions"
          render={renderActions}
          styleName="actions"
          width="150px"
        />
      </Table>
    ) : null}

    <ApplyRecords
      contactId={showingRecords?.contactId ?? null}
      onClose={() => setShowingRecords(null)}
    />
  </div>
}
